package com.qding.cupms.admin.rest.shiro;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;

import com.qding.cupms.admin.rest.redis.SessionRedisTemplate;
import com.qding.cupms.common.utils.JsonUtil;

/**
 * redis 会话管理 <功能详细描述>
 * 
 * @since [产品/模块版本]
 * @author ly
 * @version v1.0 Date:2017年8月9日 上午9:42:31
 */
public class ShiroRedisSessionDao extends AbstractSessionDAO {

    private Logger logger = Logger.getLogger(ShiroRedisSessionDao.class);

    private final static String SESSSION_REIDS_TAG = "cupms_sso_server_session";

    @Autowired
    private SessionRedisTemplate redisTemplate;

//    public void init(){
//        Jackson2JsonRedisSerializer<Session> jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer<Session>(Session.class);
//        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
//    }

    @Override
    protected Serializable doCreate(Session session) {

        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        this.saveSession(session);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        if (sessionId == null) {
            logger.error("session id is null");
            return null;
        }
        try {
            String key = this.getStringKey(sessionId);
            Session s = this.redisTemplate.opsForValue().get(key);
            System.out.println("##doReadSession sessionId:" + sessionId + ", session" + JsonUtil.Java2Json(s));
            return s;
        } catch (Exception e) {
            logger.error("deserialize session failed !", e);
            return null;
        }

    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        this.saveSession(session);
    }

    /** 
     * 根据会话id   删除sessionId
     * @param sessionId
     * @author Administrator
     * Date:2017年8月11日 下午4:21:26
     */
    public void deleteById(String sessionId){
        this.redisTemplate.delete(this.getStringKey(sessionId));
    }
    
    @Override
    public void delete(Session session) {
        if (session == null || session.getId() == null) {
            logger.error("session or session id is null");
            return;
        }
        this.redisTemplate.delete(this.getStringKey(session.getId()));
    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<Session> sessions = new HashSet<Session>();

        Set<String> keys = redisTemplate.keys(SESSSION_REIDS_TAG + "*");
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                Session s = redisTemplate.opsForValue().get(key);
                sessions.add(s);
            }
        }
        return sessions;
    }

    /**
     * save session
     * 
     * @param session
     * @throws UnknownSessionException
     */
    private void saveSession(Session session) throws UnknownSessionException {
        if (session == null || session.getId() == null) {
            logger.error("session or session id is null");
            return;
        }
        String key = this.getStringKey(session.getId());
        // 会话到期时间
        long timeoutMilliseconds = session.getTimeout();

        this.redisTemplate.opsForValue().set(key, (CupmsGlobalSession)session, timeoutMilliseconds, TimeUnit.MILLISECONDS);

    }

    /**
     * 获得byte[]型的key
     * 
     * @param sessionId
     * @return
     */
    public static String getStringKey(Serializable sessionId) {
        String preKey = SESSSION_REIDS_TAG + ":" + sessionId;
        return preKey;
    }
}
